package com.ayf.payment.game.api.channel.zhuofutong.util;

import com.swwx.charm.commons.lang.utils.LogPortal;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.IOException;

/**
 * @author wwl
 * @description:
 * @date 2021/2/22 15:07
 */
public final class HttpTookit {

    public static String HttpPostWithJson(String url, String json) throws IOException {
        String returnValue = "这是默认返回值，接口调用失败";
        CloseableHttpClient httpClient = null;
        try{
            //第一步：创建HttpClient对象
            httpClient = HttpClients.createDefault();
            //第二步：创建httpPost对象
            HttpPost httpPost = new HttpPost(url);
            //第三步：给httpPost设置JSON格式的参数
            StringEntity requestEntity = new StringEntity(json,"utf-8");
            requestEntity.setContentEncoding("UTF-8");
            httpPost.setHeader("Content-type", "application/json");
            httpPost.setEntity(requestEntity);
            //第四步：发送HttpPost请求，获取返回值
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            returnValue = httpClient.execute(httpPost,responseHandler); //调接口获取返回值时，必须用此方法
        }finally {
            try {
                if (httpClient != null){
                    httpClient.close();
                }
            } catch (Exception e) {
                LogPortal.error("卓付通接口关闭httpClient出现异常",e);
            }
        }
        //第五步：处理返回值
        return returnValue;
    }

}
